package com.example.annotation.aop;

import java.lang.reflect.Method;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;


import com.example.annotation.contextholders.DynamicDataSourceContextHolder;
import com.example.annotation.myannotation.DataSourceAnnotation;

import lombok.extern.slf4j.Slf4j;

/**
 * @author fz
 * @creation time 2021/5/20
 */
@Component
@Aspect
@Slf4j
public class DataSourceAspect {

    //切入点，对所有用到这个方法的注解进行拦截
    @Pointcut("@annotation(com.example.annotation.myannotation.DataSourceAnnotation)")
    public void pointcut(){}

    //环绕通知，在方法执行前后调用
    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        //获取到方法上注解的属性值 datasource.value().name()
        DataSourceAnnotation dataSourceAnnotation = method.getAnnotation(DataSourceAnnotation.class);
        if (dataSourceAnnotation != null) {
            //将数据源类型存放到threadLocal中
            DynamicDataSourceContextHolder.setDataSourceType(dataSourceAnnotation.value().name());
        }
        try {
            //返回的是执行方法
            return joinPoint.proceed();
        } finally {
            //销毁数据源 在执行方法之后
            log.info("销毁数据源");
            DynamicDataSourceContextHolder.removeDataSourceType();
        }
    }
}
